package com.kevin.spring.tx;

import org.springframework.jdbc.datasource.DataSourceUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by loli on 2015/6/9.
 */
public class UserDaoImpl implements UserDaoInter {
    DataSource dataSource;

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public User get(int id) {
        String sql = "select * from user where id=" + id;
        User user = null;
        try {
            Connection connection = DataSourceUtils.getConnection(dataSource);
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);
            if (resultSet.next()) {
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
                user.setPassword(resultSet.getString("password"));
            }

        }catch (SQLException e){
            throw new RuntimeException(e);
        }

        return null;
    }

    @Override
    public void add(User user) {
        String sql = String.format("insert into user(name, password) values('%s', '%s')", user.getName(), user.getPassword());
        try {
            Connection connection = DataSourceUtils.getConnection(dataSource);
            Statement statement = connection.createStatement();
            statement.executeUpdate(sql);
            DataSourceUtils.releaseConnection(connection, dataSource);
        }catch (SQLException e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(User user) {
        String sql = String.format("update user set name='%s', password='%s' where id='%d'", user.getName(), user.getPassword(), user.getId());
        try {
            Connection connection = DataSourceUtils.getConnection(dataSource);
            Statement statement = connection.createStatement();
            statement.executeUpdate(sql);
        }catch (SQLException e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(User user) {
        String sql = "delete from user where id=" + user.getId();
        try {
            Connection connection = DataSourceUtils.getConnection(dataSource);
            Statement statement = connection.createStatement();
            statement.executeUpdate(sql);
        }catch(SQLException e){
            throw new RuntimeException(e);
        }
    }
}
